package ebcs.scan.common.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

public class Pdf2Img
{
	public static void main(String[] args)
	{
			String inDir = "/Users/macbook/Desktop/pdf2img/";
			String outDir = inDir;
			String pdfFile = inDir+"2.pdf";
			//String pdfFile2 = inDir+"2.pdf";
 			File file= new File(pdfFile);
 			if(!file.exists()){
 				 file.mkdirs();
 			}
 			
			//File file2= new File(pdfFile2);
			try {
				Pdf2Img.doParse(file, inDir, outDir, true);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("mkdir--->"+file.getName());
			//file.delete();
			//file2.renameTo(new File(pdfFile));
			//System.out.println("file--->"+Pdf2Img.getFileMD5(file).equals(Pdf2Img.getFileMD5(file2)));
//			System.out.println("file--->"+Pdf2Img.getFileMD5(file)+"---"+(Pdf2Img.getFileMD5(file2)));
  	 
	}
	public static String getFileMD5(File file) {
	    if (!file.isFile()) {
	        return null;
	    }
	    MessageDigest digest = null;
	    FileInputStream in = null;
	    byte buffer[] = new byte[8192];
	    int len;
	    try {
	        digest =MessageDigest.getInstance("MD5");
	        in = new FileInputStream(file);
	        while ((len = in.read(buffer)) != -1) {
	            digest.update(buffer, 0, len);
	        }
	        BigInteger bigInt = new BigInteger(1, digest.digest());
	        return bigInt.toString(16);
	    } catch (Exception e) {
	        e.printStackTrace();
	        return null;
	    } finally {
	        try {
	            in.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	}

	public static List doParse(byte[] file,String fileNames, String inDir, String outDir,boolean parseBool) throws IOException
	{

        PDDocument document = null;
        boolean failed = false;

//        LOG.info("Opening: " + file.getName());
        try
        {
            new FileOutputStream(new File(outDir,fileNames + ".parseerror")).close();
            document = PDDocument.load(file, (String)null);
            String outputPrefix = outDir + '/' + fileNames + "-";
            int numPages = document.getNumberOfPages();
            List imageList= new ArrayList<String>();
            if(!parseBool){
            	for (int i = 0; i < numPages; i++)
                {
                    String fileName =fileNames  +"-" +  (i + 1) + ".png";
                    imageList.add(fileName);
                }
            	return imageList;
            }
            if (numPages < 1)
            {
                failed = true;
//                LOG.error("file " + file.getName() + " has < 1 page");
            }
            else
            {
                new File(outDir, fileNames + ".parseerror").delete();
            }
            
            PDFRenderer renderer = new PDFRenderer(document);
            for (int i = 0; i < numPages; i++)
            {
                String fileName = outputPrefix + (i + 1) + ".png";
                new FileOutputStream(new File(fileName + ".rendererror")).close();
                BufferedImage image = renderer.renderImageWithDPI(i, 120); // Windows native DPI
                new File(fileName + ".rendererror").delete();
//                logger.info("Writing: " + fileName);
                new FileOutputStream(new File(fileName + ".writeerror")).close();
                ImageIO.write(image, "PNG", new File(fileName));
                new File(fileName + ".writeerror").delete();
                imageList.add( fileNames +"-"+(i + 1) + ".png");
            }

            //test to see whether file is destroyed in pdfbox
            new FileOutputStream( new File(outDir, fileNames+ ".saveerror")).close();
            File tmpFile = File.createTempFile("pdfbox", ".pdf");
            document.setAllSecurityToBeRemoved(true);
            document.save(tmpFile);
            new File(outDir,fileNames + ".saveerror").delete();
            new FileOutputStream(new File(outDir, fileNames+ ".reloaderror")).close();
            PDDocument.load(tmpFile, (String)null).close();
            new File(outDir, fileNames + ".reloaderror").delete();
            tmpFile.delete();
            return imageList;
        }
        catch (IOException e)
        {
            failed = true;
//            logger.error("Error converting file " + file.getName());
            throw e;
        }
        finally
        {
            if (document != null)
            {
                document.close();
            }
        }
	}
	public static List doParse( File file, String inDir, String outDir,boolean parseBool) throws IOException
	{

        PDDocument document = null;
        boolean failed = false;

//        LOG.info("Opening: " + file.getName());
        try
        {
            new FileOutputStream(new File(outDir, file.getName() + ".parseerror")).close();
            document = PDDocument.load(file, (String)null);
            String outputPrefix = outDir + '/' + file.getName() + "-";
            int numPages = document.getNumberOfPages();
            List imageList= new ArrayList<String>();
            if(!parseBool){
            	for (int i = 0; i < numPages; i++)
                {
                    String fileName =file.getName()  +"-" +  (i + 1) + ".png";
                    imageList.add(fileName);
                }
            	return imageList;
            }
            if (numPages < 1)
            {
                failed = true;
//                LOG.error("file " + file.getName() + " has < 1 page");
            }
            else
            {
                new File(outDir, file.getName() + ".parseerror").delete();
            }
            
            PDFRenderer renderer = new PDFRenderer(document);
            for (int i = 0; i < numPages; i++)
            {
                String fileName = outputPrefix + (i + 1) + ".png";
                new FileOutputStream(new File(fileName + ".rendererror")).close();
                BufferedImage image = renderer.renderImageWithDPI(i, 120); // Windows native DPI
                new File(fileName + ".rendererror").delete();
//                logger.info("Writing: " + fileName);
                new FileOutputStream(new File(fileName + ".writeerror")).close();
                ImageIO.write(image, "PNG", new File(fileName));
                new File(fileName + ".writeerror").delete();
                imageList.add( file.getName() +"-"+(i + 1) + ".png");
            }

            //test to see whether file is destroyed in pdfbox
            new FileOutputStream( new File(outDir, file.getName() + ".saveerror")).close();
            File tmpFile = File.createTempFile("pdfbox", ".pdf");
            document.setAllSecurityToBeRemoved(true);
            document.save(tmpFile);
            new File(outDir, file.getName() + ".saveerror").delete();
            new FileOutputStream(new File(outDir, file.getName() + ".reloaderror")).close();
            PDDocument.load(tmpFile, (String)null).close();
            new File(outDir, file.getName() + ".reloaderror").delete();
            tmpFile.delete();
            return imageList;
        }
        catch (IOException e)
        {
            failed = true;
//            logger.error("Error converting file " + file.getName());
            throw e;
        }
        finally
        {
            if (document != null)
            {
                document.close();
            }
        }
	}
}
